package common;

import java.awt.Color;
import java.io.File;
import main.*;

public class Level {

	private LevelData levelData;
	
	public Level( File levelFile){
		if( levelFile == null){
			levelData = getTestLevelData();
		}else{
			levelData = getLevelDataFromFile( levelFile);
		}
	}
	
	private LevelData getTestLevelData(){
		String o = "o";//empty field
		String X = "X";//wall
		String[][] fieldRow = {
				{o, o, o, o, o, o, o, o, o, o},
				{o, X, X, o, o, o, o, o, o, o},
				{o, X, X, o, o, o, o, X, o, o},
				{o, o, o, o, o, o, o, o, o, o},
				{o, o, o, o, X, o, o, o, o, o},
				{o, o, o, o, o, X, X, o, o, o},
				{o, o, o, o, o, o, X, o, o, o},
				{o, o, X, o, o, o, X, o, o, o},
				{o, X, X, X, o, o, X, o, o, o},
				{o, o, o, o, o, o, o, o, o, o},
				{o, o, o, o, o, o, o, o, o, o},
				{o, o, o, o, o, o, X, X, X, o},
				{o, o, X, o, o, X, X, X, X, o}};
		int[][] startPosition = {
				{0,0},						//P1
				{fieldRow.length,0}, 		//P2
				{0,fieldRow[0].length}};	//P3
		Color[] startColor = { Color.CYAN,   //P1
							   Color.RED,	 //P2
							   Color.BLUE};  //p3
		
		LevelData levelData = new LevelData();
		levelData.fieldRow = fieldRow;
		levelData.startPosition = startPosition;
		levelData.startColor = startColor;
		
		if( levelData.isValid()){
			return levelData;
		}else{
			System.out.println( "Error: TestLevelData is not valid");
			return null;
		}
	}
	
	private LevelData getLevelDataFromFile( File levelFile){
		LevelData levelData = new LevelData();
		/*
		 * TODO load levelfile
		 */
		if( levelData.isValid()){
			return levelData;
		}else{
			System.out.println( "Warning: LevelFile: " + levelFile.getName() + " is not valid, using TestLevel.");
			return getTestLevelData();
		}
	}
	
	public int getRowAmount(){
		return levelData.fieldRow.length;
	}
	public int getColumnAmount(){
		return levelData.fieldRow[0].length;
	}
	public Color getStartColor( int player){
		return levelData.startColor[ player];
	}
	public int[] getStartPosition( int player){
		return levelData.startPosition[player];
	}
	public String getField( int row, int col){
		return levelData.fieldRow[row][col];
	}

	private class LevelData {
		private String[][] fieldRow;
		private int[][] startPosition;
		private Color[] startColor;
		private boolean isValid(){
			//all different startcolors?
			for( int i = 0; i < 3-1; i++){
				for( int j = i+1; j < 3; j++){
					if( this.startColor[i] == this.startColor[j]){
						return false;
					}
				}
			}
			//all different startpositions?
			for( int i = 0; i < 3-1; i++){
				for( int j = i+1; j < 3; j++){
					if( this.startPosition[i][0] == this.startPosition[j][0] &&
						this.startPosition[i][1] == this.startPosition[j][1]){
						return false;
					}
				}
			}
			return true;
		}
	}

}
